package com.auxgroup.hr.front.commons.utils;

import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Util {
	
	public MD5Util() {
		
	}

    /**
     * 该段代码记录下leancloud java 加密方法
     */
    public static String leanCloudSHA512encrypt(String password,String salt) {
        String encryptText = "";
        String text = salt + password ;
        // 是否是有效字符串
        if (!StringUtils.isEmpty(text)) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
                messageDigest.update(text.getBytes());
                byte byteBuffer[] = messageDigest.digest();
                //对密文再次做512次加密
                for (int i = 0; i < 512; i++) {
                    messageDigest.update(byteBuffer);
                    byteBuffer = messageDigest.digest();
                }
                //对密文再次做base64加密
                String base64 = getBASE64_byte(byteBuffer);
                //过滤掉密文中的回车和换行符
                base64 = base64.replaceAll("(\r\n|\r|\n|\n\r)", "");
                encryptText = base64;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return encryptText;
    }

    public static String getBASE64_byte(byte[] s) {
        if (s == null)
            return null;
        return (new sun.misc.BASE64Encoder()).encode(s);
    }

	public static void main(String[] a) throws UnsupportedEncodingException {
	    System.out.println(encode("001111111"));
    }

	public static String encode(String plainText) throws UnsupportedEncodingException {
    	byte[] unencodedPassword = null;
    	unencodedPassword = plainText.getBytes("GBK");

        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            return null;
        }

        md.reset();
        md.update(unencodedPassword);

        byte[] encodedPassword = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        return buf.toString();
    }
}
